package com.wpam.scrabble.mobile.communication;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;

import com.wpam.scrabble.mobile.GameLogic;
import com.wpam.scrabble.mobile.GameResources;
import com.wpam.scrabble.mobile.R;
import com.wpam.scrabble.mobile.activities.GameSettingsActivity;
import com.wpam.scrabble.mobile.activities.WaitingForAcceptActivity;
import com.wpam.scrabble.mobile.messages.InfoMessage;
import com.wpam.scrabble.mobile.messages.Message;
import com.wpam.scrabble.mobile.messages.MoveMessage;
import com.wpam.scrabble.mobile.messages.NewLettersMessage;
import com.wpam.scrabble.mobile.messages.NewTurnMessage;
import com.wpam.scrabble.mobile.messages.StartMessage;

public class ClientMessageParserThread extends Thread {

	private MsgBuffer buffer_;
	private boolean running_;
	
	public ClientMessageParserThread(MsgBuffer buffer) {
		
		this.buffer_ = buffer;
		this.running_ = false;
	}
	
	@Override
	public void run() {
		
		buffer_.start();
		running_ = true;
		Message messageToProcess;
		GameLogic gameLogic = GameLogic.getInstance();
		while (running_) {
			messageToProcess = buffer_.take();
			assert messageToProcess.getSenderDevice() != null : "NULL message sender in ClientMessageParser, msgType = " + messageToProcess.getType();
			if (!running_)
				return;
			if (messageToProcess.getType() == Message.CONNECT
					|| messageToProcess.getType() == Message.READY
					|| messageToProcess.getType() == Message.CHANGE_LETTERS)
				assert false : "Client received message that should't come.";
			
			switch (messageToProcess.getType()) {
			case Message.INFO:
				InfoMessage message = (InfoMessage) messageToProcess;
				if (message.isRecruiting()) {
					if (message.getGameData() == null) {
						Intent waitingIntent = new Intent(CommunicationManager.getInstance().getCurrentActivity(), WaitingForAcceptActivity.class);
						waitingIntent.putExtra(GameSettingsActivity.SERVER_TYPE, message.getServerType());
						waitingIntent.putExtra(GameSettingsActivity.TURN_TIME, message.getTurnTime());
						waitingIntent.putExtra(GameSettingsActivity.WORD_CHECK, message.isWordCheck());
						CommunicationManager.getInstance().getCurrentActivity().startActivity(waitingIntent);
					} else {
						gameLogic.applyGameData(message.getGameData());
					}
				} else {
					Builder builder = new Builder(CommunicationManager.getInstance().getCurrentActivity());
					builder.setTitle(GameResources.getInstance().getResources().getString(R.string.connecting));
					builder.setMessage(GameResources.getInstance().getResources().getString(R.string.server_is_in_game));
					builder.setPositiveButton(GameResources.getInstance().getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					builder.create().show();
				}
				break;
			case Message.START:
				CommunicationManager.getInstance().startGame((StartMessage)messageToProcess);
				break;
			}
			
			if (gameLogic.isGameRunning()) {
				switch (messageToProcess.getType()) {
				case Message.NEW_TURN:
					NewTurnMessage newTurnMsg = (NewTurnMessage)messageToProcess;
					gameLogic.cancelCurrentMove();
					gameLogic.updateScoreBoard(newTurnMsg.getScoreBoard());
					if (newTurnMsg.isGameEnded())
						gameLogic.pauseGame(GameLogic.PLAYERS_DONE);
					else
						gameLogic.turnNotifier();
					break;
				case Message.MOVE:
					final MoveMessage moveMsg = (MoveMessage)messageToProcess;
					if (moveMsg.getMoveInfo() != null)
						gameLogic.applyOuterMove(moveMsg.getMoveInfo());
					gameLogic.moveNotifier(moveMsg);
					break;
				case Message.NEW_LETTERS:
					gameLogic.getGameBoard().acceptNewLetters(((NewLettersMessage)messageToProcess).getNewLetters());
					break;
				case Message.PAUSE:
					gameLogic.pauseGame(GameLogic.PLAYERS_DISCONNECTED);
					break;
				case Message.CONTINUE:
					gameLogic.resumeGame();
					break;
				case Message.GOODBYE:
					gameLogic.getGameBoard().getHandler().post(new ToastRunnable(GameResources.getInstance().getResources().getString(R.string.server_left_the_game), true));
					gameLogic.pauseGame(GameLogic.SERVER_ENDED);
					break;
				}
			}
		}
		running_ = false;
	}

	@Override
	public void interrupt() {

		running_ = false;
		buffer_.endWork();
		super.interrupt();
	}
	
}
